<?php
/**
 * 分类管理控制器
 * @author e5
 *
 */
class CategoryController extends AuthController{
	private $db;
	public function __init(){
		parent::__init();
		$this->db = K("Category");
	}
	/**
	 * 分类列表
	 */
	public function index() {
		/* $total = $this->db->count();
		$page = new Page($total,2);
		if ($total > 2){
			$pageData = $page->show();
		}else {
			$pageData = "";
		}
		$this->assign("pageData",$pageData); */
		$data = $this->db->all();
		$cData = Data::tree($data, "cname");
		$this->assign("cData",$cData);
		$this->display("cate");
	}
	/**
	 * 添加分类
	 */
	public function add(){
		if (IS_POST){
			if (!$this->db->addCate()) $this->error($this->db->error);
			$this->success("添加分类成功",U("index"));
		}
		//获得类型数据
		$tData = K("Type")->all();
		if (empty($tData)) $this->error("请先添加类型");
		$this->assign("tData",$tData);
		$this->display("addCate");
	}
	/**
	 * 添加子分类
	 */
	public function addSonCate(){
		if (IS_POST){
			if (!$this->db->addCate()) $this->error($this->db->error);
			$this->success("添加分类成功",U("index"));
		}
		//获得所有类型数据
		$tData = K("Type")->all();
		if (empty($tData)) $this->error("请先添加类型");
		$this->assign("tData",$tData);
		$this->display("addSonCate");
	}
	/**
	 * 编辑分类
	 */
	public function edit() {
		if (IS_POST){
			if (!$this->db->editCate()) $this->error($this->db->error);
			$this->success("编辑分类成功",U("index"));
		}
		//获得原数据
		$cid = Q("get.cid",0,"intval");
		$cData = $this->db->where("cid={$cid}")->find();
		if (empty($cData)) $this->error("分类不存在");
		$this->assign("cData",$cData);
		//获得所有类型数据
		$tData = K("Type")->all();
		if (empty($tData)) $this->error("请先添加类型");
		$this->assign("tData",$tData);
		//获得所有分类数据
		$cateData = $this->db->field("cid,cname,pid")->all();
		//获得不包括当前分类和其子分类的分类数据
		$cidArr = $this->db->getSonCid($cid,$cateData);
		$cidArr[] = $cid;
		$data = $this->db->where("cid NOT IN(".implode(",", $cidArr).")")->all();
		$data = Data::tree($data, "cname");
		$this->assign("cateData",$data);
		$this->display("editCate");
	}
	/**
	 * 排序分类
	 */
	public function setOrder(){
		$sortArr = Q("post.csort");
		$cidArr = Q("post.cid");
		$temp = array();
		//组合数组
		foreach ($cidArr as $k=>$v){
			$temp[$k]['cid'] = $v;
			$temp[$k]['csort'] = intval($sortArr[$k]);
		}
		//更新数据
		foreach ($temp as $v){
			$this->db->where("cid={$v['cid']}")->update(array("csort"=>$v['csort']));
		}
		$this->success("排序成功",U("index"));
	}
	/**
	 * 删除分类
	 */
	public function del() {
		$cid = Q("get.cid",0,"intval");
		//检查是否有子分类
		if ($this->db->where("pid={$cid}")->count() > 0) $this->error("请先删除本分类下的子分类");
		//检查分类中是否存在商品
		if (K("Goods")->where("vshop_category_cid={$cid}")->count() > 0) $this->error("请先删除本分类下的商品");
		//删除分类
		if ($this->db->where("cid={$cid}")->delete() != 1) $this->error("删除分类失败");
		$this->success("删除分类成功",U("index"));
	}
}